package drrr.controller;

import com.opensymphony.xwork2.ActionSupport;
import drrr.common.SpringContext;
import drrr.orm.RoomChatListEntity;
import drrr.orm.Service;
import drrr.orm.UserEntity;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Xun on 2015/5/25.
 */
public class AjaxChatHistories extends ActionSupport {
    private String result;
    private long lastLoad;
    private int roomid;
    private static SimpleDateFormat simpleDateFormat;

    public AjaxChatHistories() {
        if (simpleDateFormat == null)
            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    }

    /**
     * 接受服务器端发送数据的截止时间,TimeStamp
     *
     * @return 时间戳
     */
    public long getLastLoad() {
        return lastLoad;
    }

    public void setLastLoad(long lastLoad) {
        this.lastLoad = lastLoad;
    }

    public int getRoomid() {
        return roomid;
    }

    public void setRoomid(int roomid) {
        this.roomid = roomid;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public void getChatHistories() throws Exception {
        String sql = String.format(
                "select roomid,a.userid,time,content,user.username from roomchatlist a,user where roomid=%d and user.id=userid and UNIX_TIMESTAMP(time)>%d",
                getRoomid(), getLastLoad() / 1000);
        out(executeChatHistories(sql));
    }

    public void init() throws IOException {
        String sql = String.format(
                "select roomid,a.userid,time,content,user.username from roomchatlist a,user where roomid=%d and user.id=userid",
                getRoomid());
        out(executeChatHistories(sql));
    }

    private String executeChatHistories(String sql) {
        UserEntity userEntity = (UserEntity) ServletActionContext.getContext().getSession().get("user");
        if (userEntity == null) {
            result = "";
        } else {
            int userid = userEntity.getId();
            String username = userEntity.getUsername();
            List list = Service.query(sql);
            List<Map<String, Object>> chList = new ArrayList<>();
            for (int i = 0; i < list.size(); ++i) {
                Object[] objs = (Object[]) list.get(i);
                Map<String, Object> members = new HashMap<>();
                members.put("roomid", objs[0]);
                members.put("userid", objs[1]);
                members.put("time", ((Timestamp) objs[2]).getTime());
                members.put("content", objs[3]);
                members.put("username", objs[4]);
                chList.add(members);
            }
            Map<String, Object> jsonMap = new HashMap<>();
            jsonMap.put("userid", userid);
            jsonMap.put("roomid", getRoomid());
            jsonMap.put("lastLoad", System.currentTimeMillis());
            jsonMap.put("chatHistories", chList);
            JSONObject jsonObject = JSONObject.fromObject(jsonMap);
            result= jsonObject.toString();
        }
        return result;
    }

    private void out(String result) throws IOException {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(result);
        out.flush();
        out.close();
    }
}
